<?php
//check login
include ('include/conf.php');
require_once 'include/reader.php';
function removeFile($target_path)
{
    //when finish delete file. Se verifica daca exista (paranoia))
    if (file_exists($target_path)) {
        if (!unlink($target_path)) {
            send_error2(22, "Uploader");
        }
        //send succesfull confirmation
        send_confirmation();
    }
}
//begin selection of clienti
//verifica autentificarea
$id_connect = connect_to_database(HOST, USER, PASS, 'server_imei2');
$sesiune = mysql_real_escape_string($_POST['sesiune']);
$op = "uploadFile";
$str = "SELECT nume,tip_cont,mail,cr_ramas FROM clienti WHERE sesiune = '$sesiune'";
$result = mysql_query($str, $id_connect);
$num_rows = mysql_num_rows($result);
if ($num_rows != 1) {
    send_error2(6, $op);
}
$value = mysql_fetch_assoc($result);
$tip_cont = $value['tip_cont'];
$userMail = $value['mail'];
$user = $value['nume'];
if ($tip_cont == 'client') {
    //valabil numai la client
    $credit_ramas = $value['cr_ramas'];
}
//prelucrare fisier
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/filestore/" . basename($_FILES['Filedata']['name']);
//check extensie
$ext = substr($_FILES['Filedata']['name'], -4);
if (!in_array($ext, $allowedExt)) {
    send_error2(24, $op);
}
if (!move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path)) {
    send_error2(21, $op);
}
//begin prelucrare upload from admin
if ($tip_cont == 'admin') {
    //begin read file
    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding('CP1251');
    $data->read($target_path);
    //target path va contine numele fisierului, adica getImei sau getCreditList.
    //In functie de acestea se va stabili ce se face

    if (preg_match("/getImei/i", $target_path)) {
        //prelucrare fisier imeiuri
        for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
            //indice 1=id 2=nume, 3=imei, 4=unlock, 8=cost. Acces data $data->sheets[0]['cells'][$i][$j]
            //se cauta fiecare imei pentru care exista cod de unlock in baza de date
            $imei = $data->sheets[0]['cells'][$i][3];
			$unlock = $data->sheets[0]['cells'][$i][4];
            if (($unlock != "")&&($imei != 'ask file')) {
                //begin update data
                $str = "SELECT nume, cost FROM coduri WHERE imei='$imei' LIMIT 1";
                $result = mysql_query($str,$id_connect);
                $value = mysql_fetch_assoc($result);
                $nume = $value['nume'];
                $cost = $value['cost'];
                $data_out = time();
                //verifica if unlock is unknow
                if (strtolower($unlock) == "unknow") {
                    //refacere cont
                    $str = "UPDATE clienti SET cr_consumat=cr_consumat-$cost, cr_ramas=cr_ramas+$cost WHERE nume='$nume'";
                    $result = mysql_query($str, $id_connect);
                    //write mysql log
                    write_mysql_log($nume, "upload file1", $str, $id_connect);
                    if (!$result) {
                        removeFile($target_path);
                        send_error2(5, "Uploader");
                    }
                    //set cost egal cu zero
                    $cost = 0;
                    $str = "UPDATE coduri SET unlock_code='$unlock', data_out='$data_out', status='done', cost='$cost' WHERE imei='$imei'";
                } else {
                    $str = "UPDATE coduri SET unlock_code='$unlock', data_out='$data_out', status='done' WHERE imei='$imei'";
                }
                $result = mysql_query($str, $id_connect);
                if (!$result) {
                    removeFile($target_path);
                    send_error2(5, "Uploader");
                }
            }
        }
    }
    if (preg_match("/getCreditList/i", $target_path)) {
        $modificari = false;
        for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
            // indice 1=marca, 2=model, 3=companie, 4=pret, 5=valoare noua
            $pret_nou = $data->sheets[0]['cells'][$i][5];
            if ($pret_nou != "") {
                $marca = $data->sheets[0]['cells'][$i][1];
                $model = $data->sheets[0]['cells'][$i][2];
                $companie = $data->sheets[0]['cells'][$i][3];
                //verifica daca e numar
                if (is_numeric($pret_nou)) {
                    //se face update la pret
                    $str = "UPDATE credit SET cost='$pret_nou' WHERE marca='$marca' AND model='$model' AND companie='$companie' LIMIT 1";
                    $result = mysql_query($str, $id_connect);
                    if (!$result) {
                        send_error2(5, 'update credit list');
                    }
                    $str = "UPDATE credit_clienti SET cost='$pret_nou' WHERE marca='$marca' AND model='$model' AND companie='$companie'";
                    $result = mysql_query($str, $id_connect);
                    if (!$result) {
                        send_error2(5, 'update credit list');
                    }
                    $modificari = true;
                }
                if (is_string($pret_nou) && ($pret_nou == 'delete')) {
                    //delete credit
                    $str = "DELETE FROM credit WHERE marca='$marca' AND model='$model' AND companie='$companie' LIMIT 1";
                    $result = mysql_query($str, $id_connect);
                    if (!$result) {
                        send_error2(5, 'update credit list');
                    }
                    $str = "DELETE FROM credit_clienti WHERE marca='$marca' AND model='$model' AND companie='$companie'";
                    $result = mysql_query($str, $id_connect);
                    if (!$result) {
                        send_error2(5, 'update credit list');
                    }
                    $modificari = true;
                }
            }
        }
        if (!$modificari) {
            send_error2(5, "Nu s-a realizat nici o modificare");
        }else{
			send_confirmation();
		}
    }
}
//begin prelucrare file from client
if ($tip_cont == 'client') {
    //se verifica daca clientul mai are credit

    //se verifica dimensiunea
    $MAXIMUM_FILESIZE = 1024 * 200; //200kb
    if ($_FILES['Filedata']['size'] >= $MAXIMUM_FILESIZE) {
        removeFile($target_path);
        send_error2(21, "Uploader");
    }
    //se scoate costul
    //scade credit
    $str = "SELECT cost FROM credit_clienti WHERE marca='Nokia' AND model='All' AND companie='RPL Files' AND nume='$user'";
    $result = mysql_query($str, $id_connect);
    if (!$result) {
        send_error2(5, $op);
    }
    $value = mysql_fetch_assoc($result);
    $cost = $value['cost'];
    if ($cost > $credit_ramas) {
        //clientul nu are credit
        send_error2(0, $op);
        removeFile($target_path);
    }
    //se trimite fisierul pe mail
    $subject = "RPL File";
    $mail_to = "admin@imeiserver.es";
    $message = "RPL File pentru Nokia";
    $attach = array('file' => $target_path);
    $mailSend = send_mail($mail_to, $message, $subject, $userMail, $user, $attach);
    if ($mailSend) {
        //return succesfull mesaj. sterge file
        removeFile($target_path);
        //update credit
        $str = "UPDATE clienti SET cr_consumat=cr_consumat+$cost, cr_ramas=cr_ramas-$cost WHERE nume='$user'";
        $result = mysql_query($str, $id_connect);
        //update coduri
        $data_in = time();
        $str = "INSERT INTO coduri (nume, imei, marca, model, companie, data_in, data_out, cost, status) VALUES ('$user','ask file','ask file','','','$data_in','','$cost','wait')";
        $result = mysql_query($str, $id_connect);
        if (!$result) {
            send_error2(5);
        }
        //write mysql log
        write_mysql_log($user, "upload file2", $str, $id_connect);
        if (!$result) {
            send_error2(5, $op);
        }
        //finish
        send_confirmation();
    } else {
        removeFile($target_path);
        send_error2(23, $op, false);
    }
}
//totul este ok. Se sterge fisierul
removeFile($target_path);


?>
